package org.ccay.excel.importer.validate.impl;

import org.ccay.core.util.StringUtil;
import org.ccay.excel.importer.validate.AbstractValidator;
import org.ccay.excel.importer.validate.IStatus;

/**
 * 字符串长度校验器。
 * 	
 * @author chaowangbang
 * @since Mar 20, 2012
 */
public class StringLengthValidator extends AbstractValidator {
	
	public static final String MESSAGE_KEY = "ccay.excel.validate.stringLength.error";
	public static final String MAXLENGTH_MESSAGE_KEY = "ccay.excel.validate.stringLength.maxLength.error";
	public static final String MINLENGTH_MESSAGE_KEY = "ccay.excel.validate.stringLength.minLength.error";
	
	/**
	 * 长度的下限
	 */
	private int minLength = -1;
	
	/**
	 * 长度的上限
	 */
	private int maxLength = -1;

	/**
	 * 设置上限值。
	 * 
	 * @param maxLength
	 */
	public void setMaxLength(int maxLength) {
		this.maxLength = maxLength;
	}

	/**
	 * 设置下限值。
	 * 
	 * @param minLength
	 */
	public void setMinLength(int minLength) {
		this.minLength = minLength;
	}

	/* (non-Javadoc)
	 * @see org.ccay.excel.importer.validate.IValidator#validate(java.lang.String, org.ccay.excel.importer.validate.IValidationContext)
	 */
	public IStatus doValidate(Object value) {
			//获取utf8的长度
		int length = value==null?0:StringUtil.getUTF8Length(value.toString());
		
		if(length < minLength ) {
			super.setMessageKey(MINLENGTH_MESSAGE_KEY);
			return error();
		}
		if(length > maxLength){
			super.setMessageKey(MAXLENGTH_MESSAGE_KEY);
			return error();
		}	
		return IStatus.Ok;
	}

}
